const $token = localStorage.getItem("token");
const $userId = localStorage.getItem("userId");
const $nickName = localStorage.getItem("nickName");
const $roleRoute = JSON.parse(localStorage.getItem("roleRoute"));
const $roleId = localStorage.getItem("roleId");

/*
    线上
*/
var $baseUrl = "http://122.9.133.100:8025/elevator/";


/*
    秦浩南
*/
// var $baseUrl = "http://192.168.1.28:8025/elevator/";


/*
    任会勇
*/
// var $baseUrl = "http://rhyme.nat300.top/elevator/";
// var $baseUrl = "http://192.168.2.65:8025/elevator/";
// var $baseUrl = "http://localhost:8025/elevator/";

/*
    wy
*/
// var $baseUrl = "http://192.168.1.29:8025/elevator/";

// const $wsUrl = "211.149.129.180:8088/" + $baseUrl;



/**
 * 获取Url参数
 * @param variable
 */
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] === variable) {
            return pair[1];
        }
    }
    return (false);
}


function authorizeState() {

    // $("#tab_right dl dd:eq(2)").click();
    // $('.layui-tab-title li[lay-id]').find('.layui-tab-close').click();
    // $('#tab_right').hide();
    // $('#tab_show').hide();

    let x = $(".layui-card-body").text().indexOf("请重新登陆！");
    if (x !== -1) {
        window.opener = null;
        // window.open($baseUrl.substring(0,$baseUrl.length -1) + "_admin/login");
        window.open("/elevator_admin/login.html");
        window.close();
    }
}


function generateRandom() {
    let l1 = '';
    for (let i = 0; i < 5; i++) {
        l1 += Math.ceil(Math.random() * 10);
    }
    let l2 = dateTimeFormat(new Date(), "yyyyMMddHHmmss");
    return l2 + l1;
}


//加载websocket
function loadWebsocket() {
    let notice;

    layui.config({
        base: 'XAdmin/layui/dist/js/'
    }).extend({
        // notice: 'notice'
    });

    //使用说明
    layui.use(['notice'], function () {
        notice = layui.notice; // 允许别名 toastr

        // 初始化配置，同一样式只需要配置一次，非必须初始化，有默认配置
        notice.options = {
            closeButton: true,//显示关闭按钮
            debug: false,//启用debug
            positionClass: "toast-top-right",//弹出的位置,
            showDuration: "300",//显示的时间
            hideDuration: "1000",//消失的时间
            timeOut: "2000",//停留的时间
            extendedTimeOut: "1000",//控制时间
            showEasing: "swing",//显示时的动画缓冲方式
            hideEasing: "linear",//消失时的动画缓冲方式
            iconClass: 'toast-info', // 自定义图标，有内置，如不需要则传空 支持layui内置图标/自定义iconfont类名
            onclick: null, // 点击关闭回调
        };
    });

    setTimeout(function () {
        let websocket = null;
        if ('WebSocket' in window) {
            // websocket = new WebSocket('ws://rhyme.nat300.top/cocoker/webSocket')
            websocket = new WebSocket('ws://' + $wsUrl + 'webSocket/' + $userId)
        } else {
            notice.error('该浏览器不支持websocket！')
        }
        websocket.onopen = function (event) {
            console.log('建立链接')
        };
        websocket.onclose = function (event) {
            console.log('链接关闭')
        };
        websocket.onmessage = function (event) {
            // 服务端发送消息
            var data = JSON.parse(event.data);
            if (data.type === 'offline') {
                notice.error(data.msg + ", 3秒后退出重新登陆!");
                setTimeout(function () {
                    location.href = "login";
                }, 3000)
            }
            console.log(event)
        };
        websocket.onerror = function () {
            // notice.error('websocket通信发送错误！')
        };
        websocket.onbeforeunload = function () {
            websocket.close();
        };


        switch (websocket.readyState) {
            case WebSocket.CONNECTING:
                notice.success('已连接');
                break;
            case WebSocket.OPEN:
                notice.success('连接成功！');
                break;
            case WebSocket.CLOSING:
                notice.success('连接正在关闭！');
                break;
            case WebSocket.CLOSED:
                notice.error('连接正在关闭！');
                break;
            default:
                notice.success('...');
                // this never happens
                break;
        }

        // window.setInterval(function () {
        //     var ping = {"type": "ping"};
        //     websocket.send(JSON.stringify(ping));
        // }, 60 * 1000);

    }, 1000);

}


//读取当前时间
function writeCurrentDate() {
    var now = new Date();
    var year = now.getFullYear(); //得到年份
    var month = now.getMonth();//得到月份
    var date = now.getDate();//得到日期
    var day = now.getDay();//得到周几
    var hour = now.getHours();//得到小时
    var minu = now.getMinutes();//得到分钟
    var sec = now.getSeconds();//得到秒
    var MS = now.getMilliseconds();//获取毫秒
    var week;
    month = month + 1;
    if (month < 10) month = "0" + month;
    if (date < 10) date = "0" + date;
    if (hour < 10) hour = "0" + hour;
    if (minu < 10) minu = "0" + minu;
    if (sec < 10) sec = "0" + sec;
    if (MS < 100) MS = "0" + MS;
    var arr_week = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    week = arr_week[day];
    var time = "";
    time = year + "年" + month + "月" + date + "日" + " " + hour + ":" + minu + ":" + sec + " " + week;
    //当前日期赋值给当前日期输入框中（jQuery easyUI）
    $("#currentDate").html(time);
    //设置得到当前日期的函数的执行间隔时间，每1000毫秒刷新一次。
    let timer = setTimeout("writeCurrentDate()", 1000);
    // console.log(time);
}

function admin_add(title, url, w, h) {
    x_admin_show(title, url, w, h);
}

//不让input自动填充
let inputs = document.getElementsByTagName('input');
for(let i = 0; i < inputs.length; i++){
    inputs[i].setAttribute('autocomplete','off')
}
